package com.guangpan.springboot.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class TaskServiceImpl implements TaskService{
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Value("${web.urlPrefix}")
    private String urlPrefix;

 da
    @Override
    public void transfer(String fileName, String userId) {
        Map data = new HashMap<>();
        String pictureUrl = urlPrefix + fileName;
        data.put("userId",userId);
        data.put("pictureUrl",pictureUrl);
        System.out.println(data);
        rabbitTemplate.convertAndSend("exchange.direct","two",new JSONObject(data).toString());

    }

    @Override
    public void upload(MultipartFile file, String path, String fileName) throws IOException {
        //使用原文件名
        String realPath = path + fileName;
        System.out.println(realPath);
        File dest = new File(realPath);

        System.out.println(dest);
        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        file.transferTo(dest);
    }

    /**
     * 生成新的文件
     * @param fileName
     * @return
     */
    @Override
    public String getFileName(String fileName) {
        String uuid = UUID.randomUUID().toString().replace("-","");
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return uuid + suffix;
    }
}
